package com.lu.dao.impl;

import com.lu.dao.BaseDao;
import com.lu.dao.TypeDao;
import com.lu.pojo.Type;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TypeDaoImpl extends BaseDao implements TypeDao {
    @Override
    public List<Type> getAllType() {
        List<Type> typeList = new ArrayList<>();
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "SELECT Tid,Tname from Type";
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            if(rs!=null){
                while (rs.next()){
                    int tid = rs.getInt("TId");
                    String tname = rs.getString("TName");
                    Type type = new Type(tid,tname);
                    typeList.add(type);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con,pstmt,rs);
        }

        return typeList;
    }

    @Override
    public Type getOneType(int tid) {
        Type type = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "SELECT Tid,Tname from Type";
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            if(rs!=null){
                while (rs.next()){
                    String tname = rs.getString("TName");
                    type = new Type(tid,tname);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con,pstmt,rs);
        }
        return type;
    }

    @Override
    public int addOneType(Type type) {
        String sql = "Insert into Type(TName,CREATED_By,CREATED_Time) values(?,?,NOW())";
        Object[] parma = {type.getTname(),type.getCreatedBy()};
        return executeUpdate(sql,parma);
    }

    @Override
    public int updateOneType(Type type) {
        String sql = "update Type set TName=?,UPDATED_By=?,UPDATED_Time=NOW() where TId = ?";
        Object[] parma = {type.getTname(),type.getUpdatedBy(),type.getTid()};
        return executeUpdate(sql,parma);
    }

    @Override
    public int delOneType(int tid) {
        String sql = "DELETE from Type where TId = ?";
        Object[] parma = {tid};
        return executeUpdate(sql,parma);
    }
}
